 //
//  NetworkManager.m
//  ios-loan
//
//  Created by ys on 15/12/2017.
//  Copyright © 2017 hxhg. All rights reserved.
//

#import "NetworkManager.h"
#import "NetworkService.h"
#import "Encypt.h"
//#import "JALOANService.h"
#import "ALUtils.h"
#import "ALLog.h"
#import "ALNetUtil.h"
#import "MacroDefinition.h"
#import "MASUtilities.h"

#pragma mark - ////////////////////////////////////////////////////////////////
#pragma mark HttpRequest
@implementation HttpRequest
+ (instancetype)requestWithMethod:(HttpMethod)method {
    HttpRequest * request = [[HttpRequest alloc] init];
    request.method = method;
    return request;
}

//- (void)setUrlWithDefaultHostAndPath:(NSString *)path {
//    self.urlString = [GetEnvironmentApiByKey(@"host") stringByAppendingString:path];
//}
@end
#pragma mark - ////////////////////////////////////////////////////////////////
#pragma mark NetworkManager
@interface NetworkManager()

@property (nonatomic, copy) NSString * regID;
@property (nonatomic, copy) NSString * deviceID;
@property (nonatomic, copy) NSString * token;

@end

@implementation NetworkManager

+ (id)sharedInstance{
    static NetworkManager * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[NetworkManager alloc] init];
    });
    return instance;
}

+ (void)send:(HttpRequest *)request completionHandler:(void(^)(id responseObj, NSError *eError))completion {
    [[NetworkManager sharedInstance] send:request completionHandler:completion];
}

+ (void)upload:(HttpRequest *)request
         files:(NSArray<NSData *> *)files
      progress:(void (^)(NSProgress *uploadProgress))uploadProgressBlock completionHandler:(void(^)(id responseObj, NSError *eError))completion {
    [[NetworkManager sharedInstance] upload:request files:files progress:uploadProgressBlock completionHandler:completion];
}

+ (void)setToken:(NSString *)token {
    [[NetworkManager sharedInstance] setToken:token];
}

+ (void)setDeviceID:(NSString *)deviceID {
    [[NetworkManager sharedInstance] setDeviceID:deviceID];
}

+ (void)setRegID:(NSString *)regID {
    [[NetworkManager sharedInstance] setRegID:regID];
}

- (void)send:(HttpRequest *)request completionHandler:(void(^)(id responseObj, NSError *error))completion {
    //获取随机字符串 aesKey，默认16位
    NSString *aesKey = [Encypt getRandomAESKey];
    NSDictionary * allHeaders = [self generateHeader:aesKey];
    //补充其他属性
    NSURL * url = [NSURL URLWithString:request.urlString]; //self.urlString
    LogI(@"request url:%@", url.absoluteString);
    NSLog(@"request url:%@", url.absoluteString);
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
    urlRequest.timeoutInterval = 15.0;
    urlRequest.HTTPMethod = (request.method == HttpGet ? @"GET" : @"POST");
    urlRequest.allHTTPHeaderFields = allHeaders;
    LogV(@"http request head: %@", urlRequest.allHTTPHeaderFields);
    //post 增加body
    if (request.method == HttpPost && request.body) {
        LogV(@"%@", request.body);
        NSLog(@"request.body=%@",request.body);
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:request.body options:NSJSONWritingPrettyPrinted error:&error];
        if (error) {
              LogE(@"JSONSerialization initData error : %@",error);
              return;
        }
        //拼接body ： validate_key直接拼接json
        NSString *bodyString = [NSString stringWithFormat:@"%@%@",[ALNetUtil getValidatTimeKeyString],[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]];
        NSData * AESBody = [Encypt AESEncrypt:[bodyString dataUsingEncoding:NSUTF8StringEncoding] WithKey:aesKey];
        [urlRequest setHTTPBody:AESBody];
    }
    
//    if (![[ALUtils sharedInstance] haveNetWork]) {
//        NSString * msg = @"抱歉，服务器开小差了";
//        NSError *eError = [NSError errorWithDomain:(msg ?: @"") code:code userInfo:nil];
//        if (completion) {
//            completion(nil,eError);
//        }
//        return;
//    }
    
    [NetworkService send:urlRequest completionHandler:^(id responseObj, NSError *error) {
        [self response:responseObj err:error completion:completion];
        if (responseObj && [responseObj isKindOfClass:[NSDictionary class]]) {
            if ([[responseObj allKeys] containsObject:@"code"]) {
                NSInteger code = [responseObj[@"code"] integerValue];
                if (code == HttpSessionInvaild) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:kDidReceivedLoginOutNotification object:nil userInfo:@{@"isOffline":@(YES)}];
                }else if (code == 61011){ //61011 会话已过期
                    [[NSNotificationCenter defaultCenter] postNotificationName:kDidReceivedLoginOutNotification object:nil userInfo:@{@"BeOverdue":@(YES)}];
                }
            }
        }
    }];
}

- (void)upload:(HttpRequest *)request
         files:(NSArray<NSData *> *)files
      progress:(void (^)(NSProgress *uploadProgress))uploadProgressBlock completionHandler:(void(^)(id responseObj, NSError *eError))completion {
    if (files.count < 1) {
        LogE(@"image is null");
        return;
    }
    //获取随机字符串 aesKey，默认16位
    NSString *aesKey = [Encypt getRandomAESKey];
    NSDictionary * allHeaders = [self generateHeader:aesKey];
    //补充其他属性
    NSURL * url = [NSURL URLWithString:request.urlString]; //self.urlString
    LogI(@"request url:%@", url.absoluteString);
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
    urlRequest.timeoutInterval = 15.0;
    urlRequest.HTTPMethod = @"POST";
    urlRequest.allHTTPHeaderFields = allHeaders;
    LogV(@"http request head: %@", urlRequest.allHTTPHeaderFields);
    NSMutableData * bodyData = [NSMutableData dataWithData:[[ALNetUtil getValidatTimeKeyString] dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:files[0]];
    NSData * AESBody = [Encypt AESEncrypt:bodyData WithKey:aesKey];
    [urlRequest setHTTPBody:AESBody];
    [NetworkService send:urlRequest completionHandler:^(id responseObj, NSError *error) {
        [self response:responseObj err:error completion:completion];
    }];
    
//    //获取随机字符串 aesKey，默认16位
//    NSString *aesKey = [Encypt getRandomAESKey];
//    NSMutableDictionary * allHeaders = [NSMutableDictionary dictionaryWithDictionary:[self generateHeader:aesKey]];
//    LogI(@"request url:%@", request.urlString);
//    NSMutableURLRequest *urlRequest = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:request.urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        if (files) {
//            for (int i=0; i<files.count; i++) {
//                [formData appendPartWithFormData:files[i] name:[NSString stringWithFormat:@"loan-assistant%d", i]];
//            }
//        }
//    } error:nil];
//    urlRequest.timeoutInterval = 15.0;
//    [allHeaders setValuesForKeysWithDictionary:urlRequest.allHTTPHeaderFields];
//    urlRequest.allHTTPHeaderFields = allHeaders;
//
//    LogV(@"http request head: %@", urlRequest.allHTTPHeaderFields);
//    [NetworkService send:urlRequest progress:uploadProgressBlock completionHandler:^(id responseObj, NSError *error) {
//        [self response:responseObj err:error completion:completion];
//    }];
}

- (NSDictionary *)generateHeader:(NSString *)aesKey {
    //RSA公钥加密aesKey
    NSString *rsaStr = [aesKey RSAEncryptWithPublicKey:GetChannelApiByKey(@"PublicRSAkey")];
    if (!rsaStr.length) {
        LogE(@"RSAEncrypt Error");
        return nil;
    }
    //base64(regID:deviceID:RSA(aesKey))
    NSString * authorization = [NSString stringWithFormat:@"%@:%@:%@", self.regID, self.deviceID, rsaStr];
    LogV(@"regID:deviceID:RSA(aesKey) %@", authorization);
    NSString *base64AESKey = [Utilities encodeString:authorization];
    NSString *authorStr = [NSString stringWithFormat:@"Basic %@",base64AESKey];
    //设置header信息
    NSMutableDictionary *allHeaders = [NSMutableDictionary dictionary];
    [allHeaders setObject:@"application/text" forKey:@"Content-Type"];
    [allHeaders setObject:@"utf-8" forKey:@"charset"];
    [allHeaders setObject:self.token forKey:@"TOKEN"];
    [allHeaders setObject:authorStr forKey:@"Authorization"];
    [allHeaders setObject:[NSString stringWithFormat:@"%@,%@", [Utilities appCode], [Utilities appVersion]] forKey:@"VERSION"];
    [allHeaders setObject:@"ios" forKey:@"PLATFORM"];
    [allHeaders setObject:GetChannelApiByKey(@"Channel") forKey:@"CHANNEL"];
    return allHeaders;
}

- (void)response:(id)responseObj
             err:(NSError *)error
      completion:(void(^)(id responseObj, NSError *eError))completion{
    HttpRetCode code = HttpUnknownFail;
    //        NSString * msg = @"unknow error happen";
    NSString * msg = @"抱歉，网络开小差了";
    NSError * eError = nil;
    NSDictionary * dataContent = nil;
    if (responseObj && [responseObj isKindOfClass:[NSDictionary class]]) {
        code = [responseObj[@"code"] integerValue];
        msg = responseObj[@"msg"];
        dataContent = responseObj[@"data"];
    }
    if (error || code != HttpSuccess) {
        LogW(@"http request error code:%ld msg:%@", code, msg);
        NSLog(@"http request error code:%ld msg:%@", code, msg);
        eError = [NSError errorWithDomain:(msg ?: @"") code:code userInfo:nil];
    }else {
        LogD(@"http request success, content:%@", responseObj);
        NSLog(@"http request success, content:%@", responseObj);
    }
    completion(dataContent, eError);

}

- (NSString *)token {
    if (_token) {
        return _token;
    }
    return @"";
}

- (NSString *)regID {
    if (_regID) {
        return _regID;
    }
    return @"";
}

- (NSString *)deviceID {
    if (_deviceID) {
        return _deviceID;
    }
//    NSString * deviceID = [[JPUSHUserDefaultsController alloc] init].getDeviceID;
//    if (deviceID) {
//        _deviceID = deviceID;
//        return _deviceID;
//    }
    return @"";
}

@end
